package com.tcheung;

import com.tcheung.entity.Document;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hwpf.extractor.WordExtractor;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * WordBatchExtractor
 *
 * @author: zhangteng
 * @time: 2014/11/29 17:48
 */
public class WordBatchExtractor {

    private static Log log = LogFactory.getLog(WordBatchExtractor.class);

    /**
     * 获取文档
     *
     * @param path
     * @return
     */
    public static List<Document> getDocumentList(String path) {
        File docPath = new File(path);

        if (!docPath.exists() || !docPath.isDirectory()) {
            log.error("The Doc path not exists or it's not a directory!");
            return null;
        }

        int filesLength = docPath.listFiles().length;

        String wordText = "";
        List<Document> documentList = new ArrayList<Document>(filesLength);
        WordExtractor wordExtractor;
        InputStream is = null;
        for (int i = 1;i <= filesLength; ++i) {
            wordText = "";
            File file = new File(docPath + "/Doc" + i + ".doc");
            try {
                is = new FileInputStream(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (is != null) {
                try {
                    wordExtractor = new WordExtractor(is);
                    wordText = wordExtractor.getText();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Document document = new Document();
            document.setDocNum(i);
            document.setContent(wordText);

            documentList.add(document);
        }

        return documentList;
    }
}
